import React, { useState, useEffect } from "react";
import moment from "moment";
import {
  Form,
  Input,
  Button,
  Table,
  Space,
  Select,
  DatePicker,
  Modal,
  message
} from "antd";
import axios from "../../../http/index";
import Title from "../../../components/TitleSmall/TitelSmall";
import "./RefundDeposit.scss";
import TitelSmall from "../../../components/TitleSmall/TitelSmall";

export default function RefundDeposit() {
  const { Option } = Select;
  const [state, setState] = useState({
    selectedRowKeys: [],
  });
  const [excelData, setexcelData] = useState([]);
  const [viewDetails, setviewDetails] = useState(false);
  const [viewDetailsData, setviewDetailsData] = useState([]);

  //表单数据
  const columns = [
    {
      title: "服务单号",
      dataIndex: "service_order",
      key: "service_order",
    },
    {
      title: "申请时间",
      dataIndex: "application_time",
      key: "application_time",
      render: (text, record) => {
        let span = record.application_time;
        let timer = span.split("T");
        let datatime = timer[1].split(".");
        return (
          <div>
            {timer[0]}&nbsp;&nbsp;{datatime[0]}
          </div>
        );
      },
    },
    {
      title: "用户账号",
      dataIndex: "account",
      key: "account",
    },
    {
      title: "退款金额",
      dataIndex: "confirm_refund_amount",
      key: "confirm_refund_amount",
    },
    {
      title: "申请状态",
      key: "application_status",
      dataIndex: "application_status",
      render: (text, record) => {
        let span = "";
        if (record.application_status == "1") {
          span = <span style={{ color: "#343434" }}>待处理</span>;
        } else if (record.application_status == 2) {
          span = <span style={{ color: "green" }}>已处理</span>;
        } else if (record.application_status == 3) {
          span = <span style={{ color: "red" }}>已拒绝</span>;
        }
        return <div>{span}</div>;
      },
    },
    {
      title: "处理时间",
      dataIndex: "loasurrender_processing_time",
      key: "loasurrender_processing_time",
    },
    {
      title: "操作",
      key: "action",
      render: (text, record) => (
        <Space size="middle">
          <a onClick={() => viewDetailsBtn(record.service_order)}>查看详情</a>
        </Space>
      ),
    },
  ];

  const data = [
    {
      key: "1",
      name: "John Brown",
      age: 32,
      address: "New York No. 1 Lake Park",
      tags: ["nice", "developer"],
    },
    {
      key: "2",
      name: "Jim Green",
      age: 42,
      address: "London No. 1 Lake Park",
      tags: ["loser"],
    },
    {
      key: "3",
      name: "Joe Black",
      age: 32,
      address: "Sidney No. 1 Lake Park",
      tags: ["cool", "teacher"],
    },
  ];

  //添加key
  const addkey = (data) => {
    return data.filter((item) => (item.key = item.id));
  };

  //表格信息
  useEffect(() => {
    axios({
      method: "GET",
      url: "/system/rriskcontrolaudit/bzj/baoshaixuanchaxun",
      params: {
        page: 1,
        limits: 10,
      },
    })
      .then((res) => {
        const excdata = addkey(res.data.data);
        setexcelData(excdata);
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);

  //搜索提交
  const onFinish = (values) => {
    //返回时间格式
    let timer = "";
    if (values.applyTime) {
      timer = moment(values.applyTime._d).format("YYYY-MM-DD HH:mm:ss");
      console.log(timer);
    }
    const params = {
      application_status: values.status || "",
      application_time: timer || "",
      service_order: values.user || "",
      page: 1,
      limits: 10,
    };
    console.log("Success:", params);
    axios({
      method: "GET",
      url: "/system/rriskcontrolaudit/bzj/baoshaixuanchaxun",
      params,
    })
      .then((res) => {
        console.log("搜索返回", res.data.data);
        const excdata = addkey(res.data.data);
        setexcelData(excdata);
      })
      .catch((err) => {
        console.log(err);
      });
  };

  //多选框的选中
  const onSelectChange = (selectedRowKeys) => {
    console.log("selectedRowKeys changed: ", selectedRowKeys);
    setState({ selectedRowKeys });
  };

  const { selectedRowKeys } = state;
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const hasSelected = selectedRowKeys.length > 0;

  //时间处理
  function range(start, end) {
    const result = [];
    for (let i = start; i > end; i++) {
      result.push(i);
    }
    return result;
  }
  function disabledDate(current) {
    // Can not select days before today and today
    return current && current > moment().endOf("day");
  }
  function disabledDateTime() {
    return {
      disabledHours: () => range(0, 24).splice(4, 20),
      disabledMinutes: () => range(30, 60),
      disabledSeconds: () => [55, 56],
    };
  }

  //处理查看订单详情的数据
  const changeTime = (time) => {
    let timer = time.split("T");
    let datatime = timer[1].split(".");
    return timer[0] + "  " + datatime[0];
  };
  const datachange = (data) => {
    for (var i = 0; i < data.length; i++) {
      data[i].application_time = changeTime(data[i].application_time);
      if (data[i].refund_type == 1) {
        data[i].refund_type = "取消订单";
      }
      if (data[i].application_status == 1) {
        data[i].application_status = "待处理";
      } else if (data[i].application_status == 2) {
        data[i].application_status = "已处理";
      } else if (data[i].application_status == 3) {
        data[i].application_status = "已拒绝";
      }
    }
    return data;
  };

  //弹窗按钮
  const viewDetailsBtn = (service_order) => {
    console.log(service_order);
    axios({
      method: "GET",
      url: "/system/rriskcontrolaudit/bzj/baochakanxiangqing",
      params: {
        service_order,
      },
    })
      .then((res) => {
        const tandate = [res.data.data];
        setviewDetailsData(datachange(tandate));
        console.log("转为数组", viewDetailsData);
      })
      .catch((err) => {
        //console.log(err);
      });
    setviewDetails(true);
  };
  // 弹窗
  const handleCancel = () => {
    setviewDetails(false);
  };

  //退款点击
  const refundEvent = (e,order) => {
    console.log(e,order);
    axios({
      method: "GET",
      url: "/system/rriskcontrolaudit/bzj/baochakanxiangqing",
      params: {
        application_time:e,
        service_order:order,
      },
    })
      .then((res) => {
        console.log(res)
        message.success("操作成功");
      })
      .catch((err) => {
        //console.log(err);
      });
    setviewDetails(false);
  };

  return (
    <div>
      <TitelSmall type="筛选查询"></TitelSmall>
      <div className="50">
        <Form onFinish={onFinish} className="select-box">
          <Form.Item label="输入搜索" name="user" style={{ width: "250px" }}>
            <Input allowClear placeholder="服务单号"></Input>
          </Form.Item>
          <Form.Item
            label="申请时间"
            name="applyTime"
            style={{ width: "250px" }}
          >
            <DatePicker
              format="YYYY-MM-DD HH:mm:ss"
              disabledDate={disabledDate}
              disabledTime={disabledDateTime}
              showTime={{ defaultValue: moment("00:00:00", "HH:mm:ss") }}
            />
          </Form.Item>

          <Form.Item label="处理状态" name="status" style={{ width: "320px" }}>
            <Select
              showSearch
              allowClear
              style={{ width: 200 }}
              placeholder="请选择处理状态"
              optionFilterProp="children"
              filterOption={(input, option) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
              filterSort={(optionA, optionB) =>
                optionA.children
                  .toLowerCase()
                  .localeCompare(optionB.children.toLowerCase())
              }
            >
              <Option value="1">待处理</Option>
              <Option value="2">已处理</Option>
              <Option value="3">已拒绝</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Button
              htmlType="submit"
              style={{
                width: "120px",
              }}
              className="login-form-button"
            >
              搜索
            </Button>
          </Form.Item>
        </Form>
      </div>
      <TitelSmall type="数据列表"></TitelSmall>
      <div style={{ marginBottom: 16 }} className="buton-box">
        <div style={{ marginLeft: 8 }}>
          <span>
            {hasSelected
              ? `当前选中 ${selectedRowKeys.length} 条数据`
              : "暂未选中"}
          </span>
        </div>
      </div>
      <Table
        rowSelection={rowSelection}
        columns={columns}
        dataSource={excelData}
      />
      {/* 查看订单详情 */}
      <Modal
        title="查看订单详情"
        visible={viewDetails}
        onCancel={handleCancel}
        width={1000}
        footer={null}
      >
        <Title type="服务单详情"></Title>
        {viewDetailsData.map((item) => (
          <div key={item.id}>
            <div className="serve-box">
              <div className="servebox-title">服务单号</div>
              <div className="servebox-txt">{item.service_order}</div>
            </div>
            <div className="serve-box">
              <div className="servebox-title">订单状态</div>
              <div className="servebox-txt">{item.application_status}</div>
            </div>
            <div className="serve-box">
              <div className="servebox-title">订单编号</div>
              <div className="servebox-txt">{item.liid}</div>
            </div>
            <div className="serve-box">
              <div className="servebox-title">申请时间</div>
              <div className="servebox-txt">{item.application_time}</div>
            </div>
            <div className="serve-box">
              <div className="servebox-title">用户账号</div>
              <div className="servebox-txt">{item.user_information_id}</div>
            </div>
            <div className="serve-box">
              <div className="servebox-title">订单金额</div>
              <div className="servebox-txt">{item.order_amount}</div>
            </div>
            <div className="serve-box">
              <div className="servebox-title">确认退款金额</div>
              <div className="servebox-txt">{item.confirm_refund_amount}</div>
            </div>
            <div className="serve-box">
              <div className="servebox-title">退款方式</div>
              <div className="servebox-txt">{item.refund_method}</div>
            </div>
            <div className="serve-box">
              <div className="servebox-title">退款类型</div>
              <div className="servebox-txt">{item.refund_type}</div>
            </div>
            <div className="serve-box">
              <div className="servebox-title">退款原因</div>
              <div className="servebox-txt">{item.refund_reason}</div>
            </div>
            <div className="serve-box">
              <div className="servebox-title">处理备注</div>
              <Input type="text" />
            </div>
            <div className="refund-btn">
              <Button
                type="primary"
                style={{ background: "green" }}
                onClick={() => refundEvent(1,item.service_order)}
              >
                确认退款
              </Button>
              <Button type="danger" onClick={() => refundEvent(2,item.service_order)}>
                拒绝退款
              </Button>
            </div>
          </div>
        ))}
      </Modal>
    </div>
  );
}
